const Service = require('egg').Service;
const jwt = require('jsonwebtoken')
class DemoService extends Service {
  async index() {
    const { app } = this;
  }
  async login() {
    const { stuid, username, password } = this.ctx.request.body;
    console.log(this.ctx.helper.getPassword(123), '密码')
    let sql = `select * from student_info where 1=1 `
    if (stuid) {
      sql += `and stuid='${stuid}' and password='${this.ctx.helper.getPassword(password)}'`
    } else {
      sql += `and username='${username}' and password='${this.ctx.helper.getPassword(password)}'`
    }
    const data = await this.app.mysql.query(sql)
    const token = jwt.sign({ ...data[0] }, this.app.config.keys, { expiresIn: '1h' })
    if (data.length) { // 密码
      return { code: 0, token }
    } else {
      return { code: -1 }
    }
  }

  async register() {
    const { stuid, username, password } = this.ctx.request.body;
    const data = await this.app.mysql.get('student_info', { username })
    if (data) {
      return { code: -1 }
    } else {
      const data = await this.app.mysql.insert('student_info', { stuid, username, password: this.ctx.helper.getPassword(password) })
      return { code: 0, data }
    }
  }
}

module.exports = DemoService;